<template>
  <div class="main">
    <a-form id="formLogin" class="user-layout-login" :model="formRef" @submit="handleSubmit">
      <a-tabs :active-key="customActiveKey" :tab-bar-style="{ textAlign: 'center', borderBottom: 'unset' }" centered
        @change="handleTabClick">
        <!-- 账户密码登录 -->
        <a-tab-pane key="tab1" :tab="$t('user.login.tab-login-credentials')">
          <a-alert v-if="isLoginError" type="error" show-icon style="margin-bottom: -10px" :message="errMsg" />
          <img src="@/assets/login/loginHr.png" alt="" class="loginHr">
          <a-form-item v-bind="validateInfos.username">
            <a-input v-model:value="formRef.username" size="large" type="text"
              :placeholder="$t('user.login.username.placeholder')">
              <template #prefix>
                <UserOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
              </template>
            </a-input>
            <!-- <input type="text" style="border:1px solid blue" placeholder="请输入账号"> -->
          </a-form-item>

          <a-form-item v-bind="validateInfos.password">
            <a-input-password v-model:value="formRef.password" size="large"
              :placeholder="$t('user.login.password.placeholder')">
              <template #prefix>
                <LockOutlined :style="{ color: 'rgba(0,0,0,.25)' }" />
              </template>
            </a-input-password>
          </a-form-item>
          <div>
            <a-checkbox v-model:checked="formRef.rememberMe" style="color:#fff">记住密码</a-checkbox>
            <span style="
                float: right;
                font-size: 14px;
                color: rgb(252, 252, 253);
                font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue,
                  Arial, Noto Sans, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol,
                  Noto Color Emoji;
              ">申请注册</span>
          </div>
        </a-tab-pane>
      </a-tabs>

      <a-form-item style="margin-top: 20px">
        <a-button size="large" type="primary" html-type="submit" class="login-button" :loading="state.loginBtn"
          :disabled="state.loginBtn">{{ $t('user.login.login') }}</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, UnwrapRef, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { Form } from 'ant-design-vue'
import { loginSuccess } from './helper'
import { useRouter } from 'vue-router'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { FormState } from './types'
import { getCurrentInstance } from 'vue'
export default defineComponent({
  components: {
    UserOutlined,
    LockOutlined
  },
  setup() {
    const useForm = Form.useForm
    const { t } = useI18n()
    const router = useRouter()

    const state = reactive({
      time: 60,
      loginBtn: false,
      loginType: 0,
      smsSendBtn: false
    })
    // #region 表单相关
    const formRef: UnwrapRef<FormState> = reactive({
      rememberMe: false,
      username: '',
      password: '',
      mobile: '',
      captcha: ''
    })
    const rulesRef = reactive({
      rememberMe: [{ trigger: 'checked' }],
      username: [
        {
          required: true,
          message: t('user.username.required')
        }
      ],
      password: [{ required: true, message: t('user.password.required') }, {}]
    })
    onMounted(() => {
      const storageStr_ = localStorage.getItem('formRef_')
      let formRef_ = {
        username: '',
        password: '',
        rememberMe: false,
        timeOut: 0
      }
      if (storageStr_) {
        const storageObj_ = JSON.parse(storageStr_)
        formRef_ = { ...storageObj_ }
        console.log(new Date().getTime())
        console.log(formRef_.timeOut)
        console.log(new Date().getTime() - formRef_.timeOut)

        if (new Date().getTime() - formRef_.timeOut > 1000 * 60 * 30) {
          console.log('已过期')
          localStorage.removeItem('formRef_')
          formRef.username = ''
          formRef.password = ''
          formRef.rememberMe = false
        } else {
          console.log('未过期')
          formRef.username = formRef_.username
          formRef.password = formRef_.password
          formRef.rememberMe = formRef_.rememberMe
        }
      } else {
        return
      }
    })
    const { validate, validateInfos } = useForm(formRef, rulesRef)
    const isLoginError = ref(false)
    let $api = getCurrentInstance()?.appContext.config.globalProperties.$api
    const errMsg = ref(null)
    const handleSubmit = (e: Event) => {
      e.preventDefault()
      state.loginBtn = true
      const validateFieldsKey =
        customActiveKey.value === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']
      validate(validateFieldsKey)
        .then(async () => {
          if (formRef.rememberMe) {
            const formRef_ = Object.assign({ ...formRef }, { timeOut: new Date().getTime() })
            localStorage.setItem('formRef_', JSON.stringify(formRef_))
            message.validate('This is an error message');
          } else {
            localStorage.removeItem('formRef_')
          }
          let data = {
            userName: formRef.username,
            password: formRef.password
          }
          $api
            .POST('/realm/session/login', data, { notice: false })
            .then((r) => {
              loginSuccess(r, router)
                .then((res) => {
                  // router.push({ path: '/appSelect' })
                  router.push({ path: '/appSelect' })
                })
                .catch((e) => {
                  isLoginError.value = true
                  errMsg.value = e.message
                  state.loginBtn = false
                })
            })
            .catch((e) => {
              isLoginError.value = true
              errMsg.value = e.message
              state.loginBtn = false
            })
        })
        .catch((e) => {
          state.loginBtn = false
        })
    }
    // #endregion

    //#region 切换tab
    const customActiveKey = ref<string>('tab1')
    const handleTabClick = (key: string) => {
      customActiveKey.value = key
    }
    //#endregion

    const requiredTwoStepCaptcha = ref<number>(0)
    const stepCaptchaVisible = ref<boolean>(false)
    return {
      formRef,
      rulesRef,
      state,
      customActiveKey,
      errMsg,
      requiredTwoStepCaptcha,
      stepCaptchaVisible,
      handleTabClick,
      handleSubmit,
      isLoginError,
      validateInfos
    }
  }
})
</script>

<style lang="less" scoped>
@import '../../style/colors.less';

input {
  width: 100%;
  background-color: rgba(1, 10, 61, 0.5);
  border: 1px solid rgba(1, 10, 61, 0.5);
  height: 40px;
}

.user-layout-login {
  width: 18%;
  margin: auto;
  z-index: 20;

  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .anticon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: var(--skrivet-primary-color);
      }
    }

    .register {
      float: right;
    }
  }
}

::v-deep(.ant-form-item-control-input-content) {
  // border: 1px solid blue;
  // background-color: rgba(255, 255, 255, 0);
  color: #fff;
}

::v-deep(.ant-input-affix-wrapper-lg) {
  background-color: rgba(1, 10, 61, 0.5);
  color: #fff;
}

::v-deep(.ant-input-suffix) {
  color: #fff;
}

::v-deep(.ant-input-affix-wrapper>input.ant-input) {
  background-color: rgba(1, 10, 61, 0.5);
  color: #fff;
}

::v-deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
  font-size: 29px;
  // padding-bottom: 20px;
  color: #fff;
}

::v-deep(.ant-tabs-ink-bar-animated) {
  width: 0 !important;
}

::v-deep(.ant-tabs-nav-wrap) {
  border: none !important;
}

::v-deep(.ant-tabs-top>.ant-tabs-nav:before) {
  border-bottom: none;
}

.loginHr {
  margin-bottom: 40px;
}

::v-deep(.anticon svg) {
  color: #fff;
}

::v-deep(.ant-alert .ant-alert-error) {
  display: none;
}
</style>
